﻿package com.projects.xenia;


import java.io.File;
import java.util.HashMap;

import com.projects.xenia.MainGoodsCatalogActivity.EfficientAdapter;
import com.projects.xenia.add_activities.Activity_InfoTabs;
import com.projects.xenia.documents_classes.Documents_Visit;
import com.projects.xenia.global_modules.MainGlobalModule;

import android.app.ListActivity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Vibrator;

import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

public class MainCustomersListActivity extends ListActivity  {	
	
	private EfficientAdapter adap;
	
	private String id;
	private String descr;
	private String adress;
	private String telephone;
	private String email;
	private String outletdescr;
	private String outletadress;
	private String outlettelephone;
	private String opentime;
	private String closetime;
	private String breacktimefrom;
	private String breacktimeto;
	private String area_id;
	private Cursor CustomersCursor;
	
	private int OpenMode;
	
	private TextView CustomerSearch_Prompt;
	private ImageView CustomerSearch_Go;
	private ImageView CustomerSearch_Reset;
	private ImageView CustomerSearch_BackWard;
	private SlidingDrawer FormSlidingDrawer;
	
	private Context Ctx;
	
	private HashMap <String , VisitItem> CustomerVisits;
	
	private class VisitItem {
		
		public String customer_id; 
		public int visit_state;
		
	}	
	
	private void GetVisits () {
	
		CustomerVisits = new HashMap<String, VisitItem>();
		
		Cursor VisitsCursor = MainGlobalModule.DBE.rawQuery("select customers_id, visit_state from xdoc_visits_h where date (date_create) = date ('now') ", null); 
		if (VisitsCursor.getCount()>0) {
			VisitsCursor.moveToFirst();
			while (!VisitsCursor.isAfterLast()){				
				VisitItem vIt = new VisitItem ();
				vIt.customer_id = VisitsCursor.getString(0); 
				vIt.visit_state = VisitsCursor.getInt(1);
				CustomerVisits.put(vIt.customer_id, vIt);
				VisitsCursor.moveToNext();
			}
			VisitsCursor.close();
		}
		
	}
	
	private boolean CheckVisit () {
		
		boolean _result = true;
		
		VisitItem vIt = CustomerVisits.get(id);		
		if (vIt!=null) {
			if (vIt.visit_state<2) {
				_result = false;
				Toast.makeText(Ctx, "Нельзя выбрать этого клиента вне визита!", Toast.LENGTH_LONG).show();
			}
		}
		
		return _result;
		
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long position_id) {	
		super.onListItemClick(l, v, position, position_id);
		
		adap.getItem(position);
		
		if ((OpenMode==1) & (CheckVisit ())) {			
			Intent DataIntent = new Intent (); 
			DataIntent.putExtra("customer_id",id);						
			DataIntent.putExtra("customer_descr",descr+","+outletdescr+","+outletadress);
			setResult(RESULT_OK, DataIntent);
			finish ();
			
		}
	}
	
	
	
	public void GetCustomersCursor (String SearchString) {
		
		try {
			 	if (SearchString.equals("")==true) {
			 		CustomersCursor = MainGlobalModule.DBE.rawQuery("SELECT id,descr,adress,telephone,email,outletdescr,outletadress,outlettelephone,opentime,closetime,breacktimefrom,breacktimeto,area_id FROM xref_Customers ORDER BY descr", null);	
			 	}
			 	else
			 	{
			 		SearchString = "%"+SearchString.toLowerCase()+"%";
			 		CustomersCursor = MainGlobalModule.DBE.rawQuery("SELECT id,descr,adress,telephone,email,outletdescr,outletadress,outlettelephone,opentime,closetime,breacktimefrom,breacktimeto,area_id FROM xref_Customers where searchdescr like ? ORDER BY descr", new String [] {SearchString});
			 	}
			
			} catch (Exception e) {
		}		
		
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);            
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.customers_form);

		CustomerSearch_Prompt = (TextView)findViewById(R.id.Customer_SearchPromt);
		CustomerSearch_Go = (ImageView)findViewById(R.id.Customer_SearchGo);
		CustomerSearch_Go.setOnClickListener(CustomerSearch_Go_Click);
		
		CustomerSearch_Reset = (ImageView)findViewById(R.id.Customer_SearchReset);
		CustomerSearch_Reset.setOnClickListener(CustomerSearch_Reset_Click);
		
		CustomerSearch_BackWard = (ImageView)findViewById(R.id.cust_backward);
		CustomerSearch_BackWard.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		GetVisits ();
		 
		GetCustomersCursor ("");
		
		FormSlidingDrawer = (SlidingDrawer)findViewById(R.id.slidingDrawer1);	
		
		
		adap = new EfficientAdapter(this);
		setListAdapter(adap);
		
		if  (getIntent().hasExtra("customer_id")) {			
			OpenMode = 1;			
		}
		else	{
			OpenMode = 0;
		}
		
		Ctx = this;
		
		getListView().setOnItemLongClickListener(onListItemLongClick);
		
		MainGlobalModule.setBackGround(getListView());
	    
	}	
	
	
	private OnItemLongClickListener onListItemLongClick = new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int position, long arg3) {		
			adap.getItem(position);		
			
			Intent InfoTabs = new Intent ();
			InfoTabs.setClass(Ctx,Activity_InfoTabs.class);		
			InfoTabs.putExtra("customer_id", id);
			InfoTabs.putExtra("dayofroute",0);
			InfoTabs.putExtra("journaltab", OpenMode == 0);
			startActivityForResult(InfoTabs, 0);
			
			return true;
			
		}
		
	};
	
	private void HideSearch () {
		
		adap.notifyDataSetChanged();
		FormSlidingDrawer.close();
		
		Context context = getApplicationContext();
		InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(CustomerSearch_Prompt.getWindowToken(), 0);
		
		Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vb.vibrate(30);
		
	}
	
	private OnClickListener CustomerSearch_Go_Click = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			GetCustomersCursor (CustomerSearch_Prompt.getText().toString());
			HideSearch ();
		}
	}; 
	
	private OnClickListener CustomerSearch_Reset_Click = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			GetCustomersCursor ("");
			CustomerSearch_Prompt.setText("");
			HideSearch ();
		}
	}; 
	
	
	
	public class EfficientAdapter extends BaseAdapter  {
		
		private LayoutInflater mInflater;
		public Context context;
		 
		public EfficientAdapter(Context context) {
		// Cache the LayoutInflate to avoid asking for a new one each time.
		mInflater = LayoutInflater.from(context);
		this.context = context;
		}
		 
		public View getView(final int position, View convertView, ViewGroup parent) {

		ViewHolder holder;
		
		if (convertView == null) {
			
		convertView = mInflater.inflate(R.layout.customers_form_list, null);
		
		holder = new ViewHolder();
		
		holder.FolderImageLine = (ImageView) convertView.findViewById(R.id.folderImageLine);
		holder.CustomerTextLine =(TextView) convertView.findViewById(R.id.CustomersTextLine); 
		holder.CustomerDetailsTextLine=(TextView) convertView.findViewById(R.id.CustomerDetails);
				
		
		convertView.setTag(holder);
		
		}
		
		else
			
		{
		holder = (ViewHolder) convertView.getTag();
		}		 
		
		
		getItem(position);		
		
		holder.FolderImageLine.setImageResource(R.drawable.ic_customerfolder);
		
		VisitItem vIt = CustomerVisits.get(id);
		int st_vit = -1;
		if (vIt!=null) {
			st_vit = vIt.visit_state;	
		}
		
		switch (st_vit) {
		case 0:
			holder.FolderImageLine.setImageResource(R.drawable.ic_visit_black);
			break;
		case 1:
			holder.FolderImageLine.setImageResource(R.drawable.ic_visit_yellow);
			break;
		case 2:
			holder.FolderImageLine.setImageResource(R.drawable.ic_visit_green);
			break;
		case 3:
			holder.FolderImageLine.setImageResource(R.drawable.ic_visit_red);
			break;				
		};
		
		
		holder.CustomerTextLine.setText(descr); 
		holder.CustomerDetailsTextLine.setText(outletdescr+","+outletadress);				
		
		return convertView;
		
		}
		 
		class ViewHolder {
			ImageView FolderImageLine;
			TextView CustomerTextLine;		
			TextView CustomerDetailsTextLine;		
		}
		 
				 
		@Override
		public long getItemId(int position) {

		return 0;
		}
		 
		@Override
		public int getCount() {

		return CustomersCursor.getCount();
		}
		 
		@Override
		public Object getItem(int position) {
			
			CustomersCursor.moveToPosition(position);
			
			id = CustomersCursor.getString(0);
			descr = CustomersCursor.getString(1);
			adress = CustomersCursor.getString(2);			
			telephone = CustomersCursor.getString(3);
			email = CustomersCursor.getString(4);
			outletdescr = CustomersCursor.getString(5);
			outletadress = CustomersCursor.getString(6);
			outlettelephone = CustomersCursor.getString(7);
			opentime = CustomersCursor.getString(8);
			closetime = CustomersCursor.getString(9);
			breacktimefrom = CustomersCursor.getString(10);
			breacktimeto = CustomersCursor.getString(11);
			area_id = CustomersCursor.getString(12);
			
		return id;
		
		}
		
		private class OnItemClickListener implements OnClickListener {
			
		    private int mPosition;
		    OnItemClickListener(int position){
		        mPosition = position;		        
		    }
		    
		    @Override
		    public void onClick(View v) {	        			        	  
	        	  
		    }       
		    
		}	
}
	
	
}
